
var _ = require('lodash'),
    Q = require('q'),
    terminalController = require('../../../CBO/server/controllers/Terminal.server.controller'),
    stationWorkController = require('../../../Initialize/server/controllers/StationWork.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    stationUserController = require('../../../Initialize/server/controllers/StationUser.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller');

exports.processScan = function(req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode,
        terminalUniqueID = parameter.TerminalUniqueID;

    var bizRecord = {
            BusinessStatus: parameter.BusinessStatus
        };
    queryHardwareInfo(terminalUniqueID).then(function (hardwareInfo) {
        _.merge(bizRecord, hardwareInfo);
        return queryOperation(barcode, bizRecord.Work);
    }).then(function (operation) {
        _.merge(bizRecord, operation);
        return queryUsers(bizRecord.WorkLocation, bizRecord.Terminal);
    }).then(function (users) {
        if (users) {
            _.merge(bizRecord, { Users: users });
        }
        return writeData(barcode, bizRecord);
    }).then(function (result) {
        res.json({
            Data: result,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

exports.insertBizRecordST = function(req, res) {
    var parameter = req.body,
        barcode = parameter.Barcode,
        terminalUniqueID = parameter.TerminalUniqueID;

    var bizRecord = {
            BusinessStatus: parameter.BusinessStatus ? parameter.BusinessStatus : 0
        };
    queryHardwareInfo(terminalUniqueID).then(function (hardwareInfo) {
        _.merge(bizRecord, hardwareInfo);
        return queryOperation(barcode, bizRecord.Work);
    }).then(function (operation) {
        _.merge(bizRecord, operation);
        return queryUsers(bizRecord.WorkLocation, bizRecord.Terminal);
    }).then(function (users) {
        if (users) {
            _.merge(bizRecord, { Users: users });
        }
        return writeData(barcode, bizRecord);
    }).then(function (result) {
        res.json({
            Data: result,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

exports.updateBizRecordST = function(req, res) {
    var parameter = req.body,
        barcode = parameter.Barcode;

    barcodeMasterController.findBarcodeMaster(barcode, function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询物料错误';
            newErr.message = '无法识别的条码，请重新扫描！';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        bizRecordController.updateOneST(record._id, function (err, result) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '更新流水错误';
                newErr.message = '更新条码流水错误！';
                res.json({
                    Data: null,
                    Error: newErr
                });
                return;
            }
            res.json({
                Data: result,
                Error: null
            });
        });
    });
};

function queryHardwareInfo (terminalUniqueID) {
    var deferred = Q.defer();

    terminalController.findByUniqueID(terminalUniqueID, function (err, terminalRecord) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (terminalRecord == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询终端错误';
            newErr.message = '请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        var hardwareInfo = {
            Terminal: terminalRecord._id,
            TerminalName: terminalRecord.Name
        };
        stationWorkController.getStationWorksByTerminalID(terminalRecord._id, function(err, stationWorkRecords) {
            if (err) {
                deferred.reject(err);
                return;
            }
            if (stationWorkRecords.length > 0) {
                hardwareInfo.WorkLocation = stationWorkRecords[0].WorkLocation._id;
                hardwareInfo.WorkLocationName = stationWorkRecords[0].WorkLocation.Name;
                hardwareInfo.Work = stationWorkRecords[0].Work._id;
                hardwareInfo.WorkName = stationWorkRecords[0].Work.Name;
            }
            deferred.resolve(hardwareInfo);
        });
    });

    return deferred.promise;
}

function queryOperation (barcode, work) {
    var deferred = Q.defer();
    
    barcodeMasterController.findBarcodeMaster(barcode, function (err, record) {
        if (err) {
            deferred.reject(err);
            return;
        }
        operationController.findByItemMasterAndWork(record.ItemMaster._id, work, function (err, result) {
            if (err) {
                deferred.reject(err);
                return;
            }
            var data = {
                BarcodeMaster: record._id
            };
            if (result) {
                _.merge(data, {
                    Operation: result._id,
                    OperationName: result.Name
                });
            }
            deferred.resolve(data);
        });
    });

    return deferred.promise;
}

function queryUsers (workLocationId, terminalId) {
    var deferred = Q.defer();

    stationUserController.findByWorkLocationAndTerminal(workLocationId, terminalId, function (err, record) {
        if (err) {
            deferred.reject(err);
            return;
        }
        deferred.resolve(record);
    });

    return deferred.promise;
}

function writeData (barcode, bizRecord) {
    var deferred = Q.defer();
    
    bizRecordController.insert(bizRecord, function (err, record) {
        if (err) {
            deferred.reject(err);
            return;
        }
        delete bizRecord.BarcodeMaster;
        barcodeMasterController.updateByValue(barcode, bizRecord, function (err, result) {
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve(result);
        });
    });

    return deferred.promise;
}